package com.yt.system.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yt.system.dao.GroupMessageMapper;
import com.yt.system.dao.RoleMapper;
import com.yt.system.domain.*;
import com.yt.system.domain.Account;
import com.yt.system.service.AccountService;
import com.yt.system.service.EmailService;
import com.yt.system.service.UserService;
import com.yt.system.utils.PageHelperUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@CrossOrigin(allowCredentials = "true")
@RestController
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    private AccountService accountService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;

    @Resource
    private GroupMessageMapper groupMessageMapper;

    @Resource
    private RoleMapper roleMapper;

    @ApiOperation(value = "登录；参数：username，password；")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username, String password, HttpServletRequest request) {
        String json = "";
        Integer flag = 0;
        System.out.println(username + "---" + password);
        // 获得当前Subject
        Subject currentUser = SecurityUtils.getSubject();
        // 验证用户是否认证，即是否登录
        if (!currentUser.isAuthenticated()) {
            String msg = "";
            // 把用户名和密码封装为 UsernamePasswordToken 对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 执行登录.
                currentUser.login(token);
            } catch (IncorrectCredentialsException e) {
                msg = "登录密码错误";
                json = hashMap(msg,flag,null,null);
                logger.error("用户"+username+"在"+new Date()+msg);
                return json;
            } catch (ExcessiveAttemptsException e) {
                msg = "登录失败次数过多";
                json = hashMap(msg,flag,null,null);
                logger.error("用户"+username+"在"+new Date()+msg);
                return json;
            } catch (LockedAccountException e) {
                msg = "帐号已被锁定";
                json = hashMap(msg,flag,null,null);
                logger.error("用户"+username+"在"+new Date()+msg);
                return json;
            } catch (ExpiredCredentialsException e) {
                msg = "帐号已过期";
                json = hashMap(msg,flag,null,null);
                logger.error("用户"+username+"在"+new Date()+msg);
                return json;
            } catch (UnknownAccountException e) {
                msg = "帐号不存在";
                json = hashMap(msg,flag,null,null);
                logger.error("账号"+username+msg);
                return json;
            }  catch (Exception e) {
                msg = "登录不成功！";
                json = hashMap(msg,flag,null,null);
                logger.error("用户"+username+"在"+new Date()+msg);
                return json;
            }
            msg = "登录成功!!!";
            flag = 1;
            //更新用户登录时间，插入当前系统时间
            accountService.updateAlogintime(new Date(),username);
            logger.info("用户"+username+"在"+new Date()+"登录成功");

            // 查看用户权限
            Account account = accountService.selectByAacount(username);
            GroupMessage groupMessage = groupMessageMapper.selectByaid(account.getAid());
            if (groupMessage==null){
                account.setGid(null);
            }else {
                account.setGid(groupMessage.getGid());
            }
            Role role = accountService.selectByAid(account.getAid());
            System.out.println("-------role----------"+role);
            if (role == null){
                //普通用户
                System.out.println("进来了1。。。。。。");
                Role role1 = roleMapper.selectByPrimaryKey(1);
                json = hashMap(msg,flag,account,role1);
            }else {
                System.out.println("进来了2。。。。。。。。");
                json = hashMap(msg,flag,account,role);
            }
            return json;
        }
        return json;
    }

    //定义一个全局变量存放验证码checkCode，static共享资源
    static String checkCode;

    /**
     * 获取验证码
     * @param email
     * @return
     */
    @ApiOperation(value = "获取验证码；参数：email；返回标志位：0代表email不存在，1代表验证码发送成功")
    @RequestMapping(value = "/getCheckCode", method = RequestMethod.POST)
    public String getCheckCode(String email){
        User user = userService.selectByEmail(email);
        String json = "";
        String msg = "";
        Integer flag = 0;
        if (user==null){
            msg = "该用户不存在，请检查一下email是否正确！";
            json = hashMap(msg,flag,null,null);
            return json;
        }
        checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的验证码为："+checkCode;
        try {
            emailService.sendSimpleMail(email, "注册验证码", message);
        }catch (Exception e){
            return "";
        }
        msg = "验证码已发送到邮箱！";
        json = hashMap(msg,flag,null,null);
        return json;
    }

    /**
     * 比对验证码
     */
    @ApiOperation(value = "比对验证码；参数：code；返回标志位：0代表验证码不正确，1代表验证码正确")
    @RequestMapping(value = "/codeCompare",method = RequestMethod.POST)
    public String codeCompare(String code){
        System.out.println("---------------------code------------------"+code);
        String msg = "";
        String json = "";
        if (!code.equals(checkCode)){
            msg = "验证码不正确！";
            json = hashMap(msg,0,null,null);
        }else {
            msg = "验证码正确！";
            json = hashMap(msg,1,null,null);
        }
        return json;
    }

    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码；参数：password；返回标志位：0代表重置不成功，1代表重置成功")
    @RequestMapping(value = "/resetPassword",method = RequestMethod.POST)
    public String resetPassword(String password, String email){
        String msg = "";
        String json = "";
        User user = userService.selectByEmail(email);
        System.out.println("---------------------password------------------"+password);
        int i = accountService.resetPassword(password, user.getUid());
        if (i > 0){
            msg = "密码重置成功！";
            json = hashMap(msg,1,null,null);
        }else {
            msg = "密码重置不成功！";
            json = hashMap(msg,0,null,null);
        }
        return json;
    }

    private String hashMap(String msg, Integer flag, Object obj1, Object obj2){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg",msg);
        map.put("flag",flag);
        if (obj1!=null){
            map.put("account",obj1);
        }if (obj2!=null){
            map.put("role",obj2);
        }
        String json = JSON.toJSONString(map);
        return json;
    }

    /**
     * 退出登录
     * @param username  账号
     * @return
     */
    @ApiOperation(value = "退出登录；参数：username；")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
       public String logout(HttpSession session, String username){
        System.out.println("-----------username------------"+username);
        accountService.updateAlogouttime(new Date(),username);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.invalidate();   //session失效
        return "退出登录";
    }

    /**
     * 修改密码
     */
    @ApiOperation(value = "修改密码；参数：aid，oldPas，newPas；返回标志位：0代表修改不成功，1代表修改成功")
    @PostMapping("/updatePassword")
    public String updatePassword(Integer aid, String oldPas, String newPas){
        System.out.println(aid+" "+oldPas+" "+newPas);
        Account account = accountService.selectByPrimaryKey(aid);
        String msg = "";
        Integer flag = 0;
        if (oldPas.equals(account.getApwd())){
            int i = accountService.resetPassword(newPas,aid);
            System.out.println("------------i-----------------"+i);
            if (i>0){
                msg = "修改密码成功";
                flag = 1;
            }else {
                msg = "修改密码失败";
            }
        }else {
            msg = "原始密码不匹配";
        }
        String json = hashMap(msg, flag, null, null);
        return json;
    }

    /**
     * 分页测试
     * @param pageQO
     * @return
     */
    @ApiOperation(value = "分页工具类测试；参数：把数据pageNum，pageSize和orderBy封装成对象pageQO，其中orderBy排序可以为空；")
    @PostMapping("/page")
    public PageVO<Object> getPage(PageQO pageQO) {
        PageHelperUtil pageHelperUtil = new PageHelperUtil();
        Page<Object> objectPage = pageHelperUtil.PageTest(pageQO);
        accountService.getAllAccount();
        PageVO<Object> pageVO = PageVO.build(objectPage);
        return pageVO;
    }

}
